//
//  PhotoLibPreviewViewController.m
//  XPhoto
//
//  Created by baboy on 2020/6/9.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "PhotoLibPreviewViewController.h"
#import "PHAsset+x.h"

@interface PhotoLibPreviewViewController ()<UIScrollViewDelegate, UIGestureRecognizerDelegate>
@property(nonatomic, strong) NSMutableDictionary *cachedPhotoViews;
@end

@implementation PhotoLibPreviewViewController
- (instancetype)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        _showCheckbox = YES;
    }
    return self;
}
- (void)dealloc{
    [self.photoLoadQueue cancelAllOperations];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    self.contentView.layer.borderColor = [UIColor redColor].CGColor;
    self.contentView.layer.borderWidth = 2;
    
    self.cachedPhotoViews = [NSMutableDictionary dictionary];
    self.photoLoadQueue = [[NSOperationQueue alloc] init];
    self.photoLoadQueue.maxConcurrentOperationCount = 1;

    if (self.selectedPhotos) {
        for (NSInteger i = 0, n = self.selectedPhotos.count; i< n;i++) {
            PHAsset *asset = [self.selectedPhotos objectAtIndex:i];
            [self addThumbWithPhoto:asset];
        }
    }
    [self updateDisplay];
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickScrollView:)];
    //设置手势属性
    tapGesture.delegate = self;
    tapGesture.numberOfTapsRequired=1;//设置点按次数，默认为1，注意在iOS中很少用双击操作
    tapGesture.numberOfTouchesRequired=1;//点按的手指数
    [self.contentView addGestureRecognizer:tapGesture];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.contentView.contentSize = CGSizeMake(self.view.bounds.size.width*self.photoCount, 0);
    [self showAtIndex:self.currentIndex];
    [self layoutThumbItemViews];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (IBAction)goBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)selectCurrentPhoto{
    PHAsset *asset = [self.photos objectAtIndex:self.currentIndex];
    BOOL selected = [self.delegate photoLibPreviewViewController:self selectAsset:asset];
    if (selected) {//[self.delegate photoLibPreviewViewController:self loadPhotoAtIndex:self.currentIndex];
        [self addSelectedPhoto:asset];
    }
    return selected;
}
- (void)deselectCurrentPhoto{
    PHAsset *asset = [self.photos objectAtIndex:self.currentIndex];
    [self.delegate photoLibPreviewViewController:self deselectAsset:asset];
    PHAsset *photoAsset = [self.photos objectAtIndex:self.currentIndex];//[self.delegate photoLibPreviewViewController:self loadPhotoAtIndex:self.currentIndex];
    [self removeSelectedPhoto:photoAsset];
}
-(IBAction)select:(UIButton*)btn{
    if (!btn.selected) {
        self.checkboxButton.selected = [self selectCurrentPhoto];
    }else{
        [self deselectCurrentPhoto];
        self.checkboxButton.selected = NO;
    }
    [self updateDisplay];
}
- (void) toggleShowNavigationBar{
    BOOL flag = self.bottomView.hidden;
    self.topView.hidden = !flag;
    self.thumbListView.superview.hidden = !flag || self.selectedPhotos.count == 0;
    self.bottomView.hidden = !flag;
}
- (void)clickScrollView:(UITapGestureRecognizer *)r{
    if (r.view == self.contentView) {
        [self toggleShowNavigationBar];
    }
}
- (void)loadPhotoAtIndex:(NSInteger)index{
    @synchronized (self) {
        NSString *k = [NSString stringWithFormat:@"%ld", index];
        BOOL cached = [self.cachedPhotoViews objectForKey:k] ? YES : NO;
        CGFloat offsetX = index * self.view.bounds.size.width;
        if (!cached) {
            
            PHAsset *photoAsset = [self.photos objectAtIndex:index];//[self.delegate photoLibPreviewViewController:self loadPhotoAtIndex:index];
            CGRect itemViewFrame = self.contentView.bounds;
            itemViewFrame.origin.x = offsetX;
            
            UIView *itemView = [self createItemViewWithAsset:photoAsset];
            itemView.frame = itemViewFrame;
            [self.contentView addSubview:itemView];
            [self.cachedPhotoViews setValue:itemView forKey:k];
        }
    }
}
- (void)showAtIndex:(NSInteger)index{
    
    CGFloat offsetX = index * self.view.bounds.size.width;
    [self.contentView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    [self preparePhotoAtIndex:index];
}
- (void)setCurrentIndex:(NSInteger)currentIndex{
    if (currentIndex == _currentIndex && self.cachedPhotoViews.count != 0) {
        return;
    }
    _currentIndex = currentIndex;
    
    PHAsset *asset = [self.photos objectAtIndex:currentIndex];//[self.delegate photoLibPreviewViewController:self loadPhotoAtIndex:currentIndex];
    BOOL selected = [self.selectedPhotos indexOfObject:asset] != NSNotFound;
    self.checkboxButton.selected = selected;
    
    BOOL shouldSelect = [self.delegate photoLibPreviewViewController:self shouldSelectAsset:asset];
//    BOOL showCheckBox = shouldSelect && photoAsset.mediaType==PHAssetMediaTypeImage;
    self.checkboxButton.hidden = !self.showCheckbox || !shouldSelect;
    [self preparePhotoAtIndex:currentIndex];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger index = lroundf( scrollView.contentOffset.x/self.view.bounds.size.width );
    self.currentIndex = index;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
}
- (void)preparePhotoAtIndex:(NSInteger)index{
    if (index > 0 && index < self.photoCount) {
        [self loadPhotoAtIndex:index-1];
    }
    if (index >=0 && index < self.photoCount) {
        [self loadPhotoAtIndex:index];
    }
    if (index >=0 && index < (self.photoCount -1)) {
        [self loadPhotoAtIndex:index+1];
    }
}

#pragma mark - selection photo
- (void)preview:(UIButton*)button{
    CGPoint offset = CGPointZero;
    offset.x = self.contentView.bounds.size.width * button.tag;
    [self.contentView setContentOffset:offset animated:YES];
    [self preparePhotoAtIndex:button.tag];
}
- (void)addThumbWithPhoto:(PHAsset *)photoAsset{
    if (!_thumbItemViews) {
        _thumbItemViews = [NSMutableArray array];
    }
    CGFloat margin = 10;
    CGFloat itemWidth = self.thumbListView.bounds.size.height - 2*margin;
    
    CGRect itemFrame = CGRectMake(margin, margin, itemWidth, itemWidth);
    UIButton *thumbButton = [[UIButton alloc] initWithFrame:itemFrame];
    [thumbButton addTarget:self action:@selector(preview:) forControlEvents:UIControlEventTouchUpInside];
    thumbButton.layer.cornerRadius = 3;
    thumbButton.clipsToBounds = YES;
    
    [self.thumbListView addSubview:thumbButton];
    [_thumbItemViews addObject:thumbButton];
    
    [[PHCachingImageManager defaultManager] requestImageForAsset:photoAsset
                                                      targetSize:CGSizeMake(itemFrame.size.width*2, itemFrame.size.height*2) contentMode:PHImageContentModeAspectFill
                                                         options:nil
                                                   resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        [thumbButton setImage:result forState:UIControlStateNormal];
        //                                                       DLOG(@"image info:%@", info);
    }];
}
- (void)addSelectedPhoto:(PHAsset *)photoAsset{
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray array];
    }
    [self addThumbWithPhoto:photoAsset];
    [_selectedPhotos addObject:photoAsset];
    [self layoutThumbItemViews];
}
- (void)removeSelectedPhoto:(PHAsset *)photoAsset{
    NSInteger i = [self.selectedPhotos indexOfObject:photoAsset];
    if(i < 0 || i >= self.selectedPhotos.count){
        return;
    }
    [self.selectedPhotos removeObjectAtIndex:i];
    UIView *v = [self.thumbItemViews objectAtIndex:i];
    [v removeFromSuperview];
    [self.thumbItemViews removeObjectAtIndex:i];
    [self layoutThumbItemViews];
}
- (void)layoutThumbItemViews{
    CGFloat margin = 10;
    CGFloat itemWidth = self.thumbListView.bounds.size.height - 2*margin;
    [UIView animateWithDuration:0.1f animations:^{
        CGRect itemFrame = CGRectMake(20, margin, itemWidth, itemWidth);
        for (NSInteger i = 0, n = self.thumbItemViews.count; i < n; i++) {
            UIView *itemView = [self.thumbItemViews objectAtIndex:i];
            itemView.frame = itemFrame;
            itemFrame.origin.x += itemFrame.size.width + margin;
        }
        self.thumbListView.contentSize = CGSizeMake(itemFrame.origin.x + 20, 0);
    }];
}
- (void)updateDisplay{
    self.thumbListView.superview.hidden = self.selectedPhotos.count == 0;
}

#pragma mark - Action
- (IBAction)enter:(id)sender{
    if (self.selectedPhotos.count == 0) {
        BOOL ret = [self selectCurrentPhoto];
        self.checkboxButton.selected = ret;
    }
    [self.delegate photoLibPreviewViewController:self didFinishAtIndex:self.currentIndex];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
